﻿using System.IO;
using System.ServiceModel.Channels;
using System.Xml;
using System.Xml.Serialization;

namespace GlimpseWcf.Core
{
    public class WcfGlimpseResponseMessageHeader : MessageHeader
    {
        private readonly WcfGlimpseResponse _response;
        private const string GlimpseWcf = "GlimpseWcf";
        private const string WcfHeader = "WcfHeader";

        public WcfGlimpseResponseMessageHeader(WcfGlimpseResponse response)
        {
            _response = response;
        }

        protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion)
        {
            var serializer = new XmlSerializer(typeof(WcfGlimpseResponse));
            var textWriter = new StringWriter();
            serializer.Serialize(textWriter, _response);
            textWriter.Close();
            writer.WriteElementString(Name, Namespace, textWriter.ToString());
        }

        public static WcfGlimpseResponse ReadHeader(Message request)
        {
            var headerPosition = request.Headers.FindHeader(WcfHeader, GlimpseWcf);
            if (headerPosition == -1)
                return null;

            string text = request.Headers.GetHeader<XmlNode[]>(headerPosition)[0].InnerText;
            var deserializer = new XmlSerializer(typeof (WcfGlimpseResponse));
            var textReader = new StringReader(text);
            var response = (WcfGlimpseResponse) deserializer.Deserialize(textReader);
            textReader.Close();

            return response;
        }

        public override string Name{ get { return WcfHeader; } }
        public override string Namespace{ get { return GlimpseWcf; } }
    }
}
